package net.ptcs.litang.controller;

import net.ptcs.litang.dao.OrderDao;
import net.ptcs.litang.entity.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class TicketServlet
 */
@WebServlet("/listOrder")
public class ListOrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置头文件
        response.setContentType("application/json; charset=utf8");
        PrintWriter out = response.getWriter();
        ResultSet result = null;
        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute("user");
        // 设置响应map
        HashMap<String, Object> hashMap = new HashMap<String, Object>();

        OrderDao orderDAO = new OrderDao();
        JSONArray dataContent = null;
        try {
            dataContent = orderDAO.selectOrderAll(user.getId());
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        if (dataContent != null) {
            hashMap.put("code", 0);
            hashMap.put("msg", "查询成功");
            hashMap.put("count", dataContent.size());
            hashMap.put("data", dataContent);
        } else {
            hashMap.put("code", 1);
            hashMap.put("msg", "查询失败");
        }

        JSONObject json = JSONObject.fromObject(hashMap);
        out.write(json.toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
}